//
//  MeViewController.m
//  Lightthings
//
//  Created by Hero on 2024/8/30.
//

#import "MeViewController.h"
#import "UIApplication+YYAdd.h"
#import "ThemeManager.h"
#import "LanguageSelectView.h"
#import "ChooseThemeViewController.h"
#import "AboutUsViewController.h"
#import "BluetoothDevicesTable+CoreDataClass.h"
#import "MyInfoViewController.h"
#import "PermissionsSet.h"

@interface MeViewController ()
/* <#note#> */
@property (nonatomic, strong) UIView * headerBgView;
@property (nonatomic, strong) UIImageView * avatarView;
@property (nonatomic, strong) UILabel * nameLab, * countLab;
@property (nonatomic, strong) CAGradientLayer * layer;

@end

@implementation MeViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [self updateHeaderViewValue];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initData];
    [self initUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTheme) name:@"k_change_theme" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateValue) name:@"k_change_userInfo" object:nil];
    
    [self updateValue];

    // Do any additional setup after loading the view.
}

- (void)updateValue {
    NSString * name = [[NSUserDefaults standardUserDefaults] valueForKey:@"_userName"];
    if (name) {
        self.nameLab.text = name;
    }else {
        self.nameLab.text = @"Lightthings";
    }
    
    NSData *data = [[NSUserDefaults standardUserDefaults] valueForKey:@"userAvatar"];
    if (data) {
        self.avatarView.image = [UIImage imageWithData:data];
    }else {
        NSString * sex = [[NSUserDefaults standardUserDefaults] valueForKey:@"_userSex"];
        if ([sex isEqualToString:@"Female"]) {
            self.avatarView.image = U_imageNamed(@"avatar_female_white");
        }else {
            self.avatarView.image = U_imageNamed(@"avatar_man_white");
        }
    }
}

- (void)initData {
    [self.dataArr addObjectsFromArray:@[@{@"name":SWString(@"Authority management"), @"img":@"icon_about_permission"},
                                        @{@"name":SWString(@"Choose language"), @"img":@"icon_about_language"},
                                        @{@"name":SWString(@"Theme settings"), @"img":@"icon_about_theme"},
                                        @{@"name":SWString(@"About us"),@"img":@"icon_about_about"},
                                        @{@"name":SWString(@"Software Version"),@"img":@"icon_about_version"}]];
}

- (void)initUI {
    
    self.tableView.frame = CGRectMake(10, kStatusBarHeight, kScreenWidth - 20, kScreenHeight - kStatusBarHeight - kTabBarHeight);
    self.tableView.tableHeaderView = self.headerBgView;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorInset = kEdge(0, 10, 0, 10);
    [self.view addSubview:self.tableView];
    
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 100)];
    [JYInitializer jy_initYellowButtonWithTarget:self action:@selector(clickQuit) frame:CGRectMake(50, 30, kScreenWidth - 100,50) title:SWString(@"退出登录") on:view layout:^(MASConstraintMaker * _Nonnull make) {
        kMakeLV(50);
        kMakeCenterXV(0);kMakeWHV(kScreenWidth - 100, 50);
    }];
//    self.tableView.tableFooterView = view;
    
    [self updateTheme];
}

- (void)updateTheme {
    self.view.backgroundColor = [ThemeManager sharedInstance].themeColor;
    
    self.layer.colors = [ThemeManager sharedInstance].themeValue == Theme_Default? @[(id)jy_HexColor(@"#041A72").CGColor, (id)jy_HexColor(@"#041A72").CGColor] : [ThemeManager sharedInstance].gradientColors;
    [self updateHeaderViewValue];
    
    [self.dataArr removeAllObjects];
    [self initData];
    [self.tableView reloadData];
}

- (void)updateHeaderViewValue {
    NSManagedObjectContext *context = [[DBManager sharedManager] managedObjectContext];

    NSFetchRequest *  request = [[NSFetchRequest alloc] initWithEntityName:@"BluetoothDevicesTable"];
    NSArray<BluetoothDevicesTable *> * result = [context executeFetchRequest:request error:nil];
    self.countLab.text = [NSString stringWithFormat:SWString(@"SW Smart Devices"), [NSString stringWithFormat:@"%ld",result.count]];
}

- (void)clickQuit{
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        cell.selectionStyle = 0;
        cell.textLabel.font = U_font(16);
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.backgroundColor = [UIColor clearColor];
    }
    
    cell.textLabel.text = self.dataArr[indexPath.row][@"name"];
    cell.imageView.image = U_imageNamed(self.dataArr[indexPath.row][@"img"]);
    cell.textLabel.textColor = [ThemeManager sharedInstance].textColor;
    if (indexPath.row == self.dataArr.count - 1) {
        cell.detailTextLabel.text = [[UIApplication sharedApplication] appVersion];
    }else {
        cell.detailTextLabel.text = nil;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        PermissionsSet * alert = [[PermissionsSet alloc] init];
        [alert show];
    }else if (indexPath.row == 1) {
        toast(SWString(@"developing"));
        return;
        LanguageSelectView * alert = [[LanguageSelectView alloc] init];
        [alert show];
    }else if (indexPath.row == 2) {
        toast(SWString(@"developing"));
        return;
        ChooseThemeViewController  * vc = [[ChooseThemeViewController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.row == 3) {
        AboutUsViewController  * vc = [[AboutUsViewController alloc] initWithNibName:@"AboutUsViewController" bundle:nil];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.row == 4) {
        toast(SWString(@"It is currently the latest version"));
    }
}

- (void)clickHeaderView {
    MyInfoViewController * vc = [[MyInfoViewController alloc] initWithNibName:@"MyInfoViewController" bundle:nil];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController: vc animated:YES];
}

- (UIView *)headerBgView {
    if (!_headerBgView) {
        _headerBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 20, 120)];
        _headerBgView.layer.cornerRadius = 10;
        _headerBgView.layer.masksToBounds = YES;
        _headerBgView.userInteractionEnabled = YES;
        _headerBgView.backgroundColor = KLColor(@"#1CAA6E");
        [_headerBgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickHeaderView)]];
    
//        CAGradientLayer * layer = [[CAGradientLayer alloc] init];
//        layer.frame = self.headerBgView.bounds;
//        layer.startPoint = CGPointMake(0, 1 );
//        layer.endPoint = CGPointMake(0, 0);
//        layer.colors = [ThemeManager sharedInstance].gradientColors;
//        _layer = layer;
//        [_headerBgView.layer insertSublayer:layer atIndex:0];
        
        _avatarView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
        _avatarView.layer.cornerRadius = 30;
        _avatarView.layer.masksToBounds =  YES;
        _avatarView.image = U_imageNamed(@"avatar01");
        _avatarView.backgroundColor = [UIColor clearColor];
        [_headerBgView addSubview:_avatarView];
        [_avatarView mas_makeConstraints:^(MASConstraintMaker *make) {
            kMakeLV(15);
            kMakeCenterYV(0);
            kMakeWHV(60, 60);
        }];
        
        _nameLab = [SWInitializer jy_initLabelWithText:SWString(@"Lightthings") textColor:jy_HexColor(@"#000000") font:U_font(14) bgColor:[UIColor clearColor] on:_headerBgView layout:^(MASConstraintMaker * _Nonnull make) {
            kMakeL(self.avatarView.mas_right).offset(15);
            kMakeT(self.avatarView.mas_top).offset(5);
        }];
        
        _countLab = [SWInitializer jy_initLabelWithText:[NSString stringWithFormat:SWString(@"SW Smart Devices"), @"0"] textColor:jy_HexColor(@"#000000") font:U_font(14) bgColor:[UIColor clearColor] on:_headerBgView layout:^(MASConstraintMaker * _Nonnull make) {
            kMakeL(self.avatarView.mas_right).offset(15);
            kMakeB(self.avatarView.mas_bottom).offset(-5);
        }];
        _countLab.zh_action = kRunCMD(@"_show_devicelist");
    }
    return _headerBgView;
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
